#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char* replace(const char* str, const char* old_sub, const char* new_sub)
 {
   int len_str = strlen(str);
   int len_old = strlen(old_sub);
   int len_new = strlen(new_sub);
   int new_len = len_str + 1;
   for (int i = 0; i < len_str; i++) 
   {
       if (strncmp(&str[i], old_sub, len_old) == 0) 
	   {
           new_len += len_new - len_old;
           i += len_old - 1;
       }
   }
   char* result = (char*)malloc(new_len * sizeof(char));
   int j = 0;
   for (int i = 0; i < len_str; i++) 
   {
       if (strncmp(&str[i], old_sub, len_old) == 0) 
	  	{
           strcpy(&result[j], new_sub);
           j += len_new;
           i += len_old - 1;
       	}
	    else 
		{
           result[j++] = str[i];
       	}
   }
   result[j] = '\0';
   return result;
}

const char * get_time()
{
    time_t current_time;
    time(&current_time);
    const char *time_string = ctime(&current_time);
	const char* old_sub = "\n";
	const char* new_sub = "";
    time_string = replace(time_string, old_sub, new_sub);
    printf("%s\n",time_string);
    return time_string;
}


const char * get_filename()
{
   const char* str = get_time();
   const char* old_sub = " ";
   const char* new_sub = "_";
   char* new_str = replace(str, old_sub, new_sub);
   strcat(new_str,"_Data.log\n");
   old_sub = ":";
   new_str = replace(new_str, old_sub, new_sub);
   printf("%s",new_str);
   return new_str;
}

FILE * create_log()
{
    const char *log_file=get_filename();
	FILE *fp;
    fp = fopen(log_file, "w+"); 
    return fp;
}


int write_log(FILE *fp,const char *log_type, const char *log_message)
{
    const char *time_string = get_time();
    fprintf(fp, "[%s] [%s] %s\n", time_string, log_type, log_message);
    return 0;
}

int main()
{
    FILE *fp = create_log();
    write_log(fp, "INFO", "This is a info log.");
    printf("Logging...\n");
    write_log(fp, "WARN", "This is a warn log.");
    printf("Logging...\n");
    write_log(fp, "ERROR", "This is a error log.");
    printf("Logging...");
    fclose(fp);
    return 0;
}
